package org.aom.litebean.module;

import java.io.IOException;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.aom.constants.ILocalStringsKey;
import org.aom.entity.menu.Module;
import org.aom.entity.menu.ModuleItem;
import org.aom.entity.security.User;
import org.aom.litebean.module.base.BaseBean;
import org.aom.service.menu.IModuleItemManager;
import org.aom.service.menu.IModuleManager;
import org.aom.service.security.IUserManager;
import org.aom.util.TagPanelUtil;
import org.aom.util.Util;
import org.operamasks.faces.annotation.Action;
import org.operamasks.faces.annotation.ActionListener;
import org.operamasks.faces.annotation.BeforeRender;
import org.operamasks.faces.annotation.Bind;
import org.operamasks.faces.annotation.ManagedBean;
import org.operamasks.faces.annotation.ManagedBeanScope;
import org.operamasks.faces.annotation.ManagedProperty;
import org.operamasks.faces.component.layout.impl.UITabLayout;
import org.operamasks.faces.component.widget.ExtConfig;
import org.operamasks.faces.component.widget.UISeparator;
import org.operamasks.faces.component.widget.UIToolBar;
import org.operamasks.faces.component.widget.menu.UICommandMenuItem;
import org.operamasks.faces.component.widget.menu.UIMenu;
import org.springside.modules.security.springsecurity.SpringSecurityUtils;

@ManagedBean(name = "module.mainFrameBean", scope = ManagedBeanScope.SESSION)
public class MainFrameBean extends BaseBean implements Serializable {

	private static final long serialVersionUID = 7862429401804006573L;
	private static ExtConfig config = new ExtConfig();
	private static ExtConfig config2 = new ExtConfig();

	static {
		config.set("closable", false);
		config.set("border", false);
		config2.set("border", false);
	}

	@ManagedProperty("#{moduleManager}")
	private IModuleManager moduleManager;

	@ManagedProperty("#{moduleItemManager}")
	private IModuleItemManager moduleItemManager;

	@ManagedProperty("#{userManager}")
	private IUserManager userManager;

	@Bind
	private UITabLayout centerPanel;

	/**
	 * 绑定页面上的ToolBar组件
	 */
	@Bind
	private UIToolBar toolBar;

	@BeforeRender
	protected void beforeRender(boolean isPostBack) {
		
		initBaseResource();
		org.springframework.security.userdetails.User securityUser = SpringSecurityUtils
				.getCurrentUser();
		String userName = securityUser.getUsername();
		User user = userManager.findByUniqueProperty("loginName", userName);
		Long expTime = user.getExpTime();
		if(expTime != 0L){
			user.setExpTime(0L);
			userManager.save(user);
		}

		if (!isPostBack) {
			List<ModuleItem> validItems = user.getMenu().getModuleItems();

			FacesContext context = FacesContext.getCurrentInstance();
			Application application = context.getApplication();

			Set<Long> mIds = getDistinctModuleIds(validItems);
			List<Module> modules = moduleManager.findEntitysByIds(mIds);
			if (modules != null) {
				for (Module module : modules) {
					// 创建菜单
					UIMenu menu = (UIMenu) application
							.createComponent(UIMenu.COMPONENT_TYPE);
					menu.setLabel(module.getName());

					List<ModuleItem> items = moduleItemManager.findBy("module",
							module);
					if (items != null) {
						for (ModuleItem item : items) {
							// 创建菜单下拉项
							UICommandMenuItem uiItem = (UICommandMenuItem) application
									.createComponent(UICommandMenuItem.COMPONENT_TYPE);
							uiItem.setLabel(item.getName());
							uiItem
									.setImage(Util.getBasePath()
											+ item.getIcon());
							uiItem.setValue(item.getUrl());
							// 添加事件监听
							uiItem
									.addActionListener(Util
											.createMethodExpressionActionListener(
													context,
													"#{module.mainFrameBean.redirect}"));
							boolean valid = false;
							for (ModuleItem moduleItem : validItems) {
								if (item.getId() == moduleItem.getId()) {
									valid = true;
									break;
								}
							}
							if (!valid) {
								uiItem.setDisabled(true);
							}
							menu.getChildren().add(uiItem);
						}
					}

					toolBar.getChildren().add(menu);
					UISeparator separator = (UISeparator) application
							.createComponent(UISeparator.COMPONENT_TYPE);
					toolBar.getChildren().add(separator);
				}

			}
			help();
		}
		String label = getMessages().get(ILocalStringsKey.WELCOME_LABEL);
		if (label != null) {// 替换占位符，将登陆用户的名称载如标语
			welcome = String.format(label, user.getName());
		}
		footerHelp = getMessages().get(ILocalStringsKey.HELP_LABEL);
		footerTermsOfUse = getMessages().get(
				ILocalStringsKey.TERMS_OF_USE_LABEL);
		footerDeclareOfLaw = getMessages().get(
				ILocalStringsKey.DECLARE_OF_LAW_LABEL);
	}

	private Set<Long> getDistinctModuleIds(List<ModuleItem> moduleItems) {
		Set<Long> mIds = new HashSet<Long>();
		for (ModuleItem mdouleItem : moduleItems) {
			mIds.add(mdouleItem.getModule().getId());
		}
		if (mIds.size() != 0) {
			return mIds;
		} else {
			return Collections.emptySet();
		}
	}

	/**
	 * 绑定帮助按钮点击事件
	 */
	@Action(id = "help")
	public void help() {
		centerPanel.addTab(getMessages().get(ILocalStringsKey.MENU_HELP_LABEL),
				"help.xhtml", "help_tpcls", config);
	}

	/**
	 * 事件监听函数，用于执行菜单按钮点击后的页面切换的脚本回调
	 * 
	 */
	@ActionListener
	public void redirect(ActionEvent e) {
		if (e.getComponent() instanceof UICommandMenuItem) {
			UICommandMenuItem item = (UICommandMenuItem) e.getComponent();
			Object obj = item.getValue();
			String url = (obj instanceof String ? (String) obj : obj.toString());
			centerPanel.addTab(item.getLabel(), url, TagPanelUtil
					.getTabPanelIconCls(item.getImage()), config2);
		}
	}

	/**
	 * 绑定注销按钮的点击事件
	 */
	@Action(id = "logout")
	public void logout() {
		ServletContext servletContext = (ServletContext) FacesContext
				.getCurrentInstance().getExternalContext().getContext();
		HttpServletRequest request = (HttpServletRequest) FacesContext
				.getCurrentInstance().getExternalContext().getRequest();
		HttpServletResponse respone = (HttpServletResponse) FacesContext
				.getCurrentInstance().getExternalContext().getResponse();
		RequestDispatcher rd = servletContext
				.getRequestDispatcher("/j_spring_security_logout");
		try {
			rd.forward(request, respone);
		} catch (ServletException e) {
		} catch (IOException e) {
		} finally {
			FacesContext.getCurrentInstance().responseComplete();
		}
	}

	/**
	 * 绑定欢迎标语Text域的值
	 */
	@SuppressWarnings("unused")
	@Bind(id = "welcome", attribute = "value")
	private String welcome;

	/**
	 * 绑定帮助链接的显示值
	 */
	@SuppressWarnings("unused")
	@Bind(id = "footerHelp", attribute = "value")
	private String footerHelp;

	/**
	 * 绑定使用条款链接的显示值
	 */
	@SuppressWarnings("unused")
	@Bind(id = "footerTermsOfUse", attribute = "value")
	private String footerTermsOfUse;

	/**
	 * 绑定法律申明链接的显示值
	 */
	@SuppressWarnings("unused")
	@Bind(id = "footerDeclareOfLaw", attribute = "value")
	private String footerDeclareOfLaw;
}
